package com.lfy.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lfy.ai.AiChatStandard;
import com.lfy.ai.AiGroupManager;
import com.lfy.ai.AiGroupNorm;
import com.lfy.ai.AiStrategyFactory;
import com.lfy.ai.anno.Dispatching;
import com.lfy.domain.dto.AskDTO;
import com.lfy.modules.ai.domain.AiModelEntity;
import com.lfy.modules.ai.service.AiModelService;
import com.lfy.modules.common.domain.BaseEnum;
import com.lfy.modules.common.domain.R;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/web/chat")
public class AiController {
    @Resource
    private AiStrategyFactory aiStrategyFactory;
    @Resource
    private ThreadPoolExecutor mainThreadPool;
    @Resource
    private AiModelService aiModelService;
/**
 * 获取大模型下的所有开通的子模型
 */
    @GetMapping("/getModelList")
    public R<List<AiModelEntity>> getModelList(@RequestParam("modelId") Integer modelId){
        List<AiModelEntity> list = this.aiModelService.list(Wrappers.lambdaQuery(AiModelEntity.class).eq(AiModelEntity::getAiId, modelId)
                .select(AiModelEntity::getAiModelKey,AiModelEntity::getAiModelName));
        return R.success(list);
    }
    /**
     * 对话分组初始化
     * @param modelId 模型ID
     * @return R
     */
    @GetMapping("/initGroup")
    public R<Integer> initGroup(@RequestParam("modelId") Integer modelId, @RequestParam("clientId") String clientId){
        AiGroupNorm aiGroup = AiGroupManager.getAiGroup(modelId);

        if(aiGroup == null){
            return R.error(BaseEnum.ChatEnum.NO_FOUND_AI);
        }
        int groupId = aiGroup.initLogin(clientId);
        return R.success(groupId);
    }
    @RequestMapping("/ask")
    @Dispatching(url = "#dto.url", message = "#dto.message",modelId = "#dto.modelId",modelType = "#dto.modelType")
    public R<Void> chat(@RequestBody @Validated AskDTO dto){
        AiChatStandard strategy = aiStrategyFactory.getStrategy(dto.getModelId());
        if(strategy == null){
            return R.error(BaseEnum.ChatEnum.NO_FOUND_AI);
        }
        mainThreadPool.execute(()->strategy.ask(dto.getMessage(),dto.getModelType(),dto.getClientId(),dto.getGroupId(),dto.getUrl()));
        return R.success();
    }
    @GetMapping("/createGroup")
    public R<Integer> createGroup(@RequestParam("modelId") Integer modelId, @RequestParam("clientId") String clientId){
        AiGroupNorm aiGroup = AiGroupManager.getAiGroup(modelId);
        if(aiGroup == null){
            return R.error(BaseEnum.ChatEnum.NO_FOUND_AI);
        }
        int groupId = aiGroup.createGroup(clientId);
        return R.success(groupId);
    }
}
